package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.RemindService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.Reception;
import com.joint.core.service.ReceptionService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/30.
 */
@ParentPackage("manage")
public class AjaxReceptionAction extends BaseFlowAction {
    @Resource
    private UsersService usersService;
    @Resource
    private ReceptionService receptionService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private RemindService remindService;

    /**
     * 附件上传
     */
    private String fileId;
    private String fileIds;
    /**
     * 公函号
     */
    private String letterNo;
    /**
     * 来宾姓名
     */
    private String guestName;
    /**
     * 性别
     */
    private String sex;
    /**
     * 来访单位
     */
    private String department;
    /**
     * 职务
     */
    private String post;
    /**
     * 主要随员
     */
    private String mainAttache;
    /**
     * 人数
     */
    private String count;
    /**
     * 主陪姓名
     */
    private String mainNameId;
    /**
     * 其他陪同人员
     */
    private String otherPerson;
    /**
     * 接待事由
     */
    private String receptionReason;
    /**
     * 接待时间
     */
    private String date;
    /**
     * 公务内容
     */
    private String content;
    /**
     * 就餐地点
     */
    private String eatPlace;
    /**
     * 就餐标准
     */
    private String eatStandard;
    /**
     * 住宿地点
     */
    private String livePlace;
    /**
     * 住宿标准
     */
    private String liveStandard;
    /**
     * 本次费用合计
     */
    private String money;
    /**
     * 其他项目
     */
    private String object;
    /**
     * 备注
     */
    private String remarks;
    /**
     * 是否上报中心
     */
    private int leaderExam;
    /**
     * 是否是产业中心人员
     */
    private int ifCentralStaff;

    private String viewtype;
    private Reception reception;
    private Users loginUser;
    private String expend;
    private String expendId;


    public String execute(){
        return "reception";
    }

    public String list(){
        pager = new Pager(0);
        /*
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
      //  params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=receptionService.findByPagerAndLimit(false, "reception", pager, params);
            }else if(viewtype.equals("2")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=receptionService.findByPagerAndFinish( "reception", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=receptionService.findByPagerAndLimit(true, "reception", pager, params);
        }
        List<Reception> receptionList;
        if (pager.getTotalCount() > 0){
            receptionList = (List<Reception>) pager.getList();
        }else{
            receptionList= new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Reception reception: receptionList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",reception.getId());
            rMap.put("year", DataUtil.DateToString(reception.getCreateDate(), "yyyy"));
            rMap.put("month", DataUtil.DateToString(reception.getCreateDate(), "MM"));
            rMap.put("guestName", reception.getGuestName());
            rMap.put("department", reception.getDepartment());
            rMap.put("mainName", reception.getMainName().getName());
            rMap.put("date", DataUtil.DateToString(reception.getDate(), "yyyy-MM-dd"));
            rMap.put("state",reception.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            fileId ="";
            reception = receptionService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            flowNumStatus = workflowService.getFlowNumStatus(keyId);
            if(reception.getFile() != null && reception.getFile().size()>0){
                for(FileManage f:reception.getFile()){
                    fileId+=f.getId()+",";
                }
            }
        }
        return "read";
    }

    public String input(){
        if(StringUtils.isNotEmpty(keyId)){
            fileId ="";
            reception=receptionService.get(keyId);
            if(reception.getFile() != null && reception.getFile().size()>0){
                for(FileManage f:reception.getFile()){
                    fileId+=f.getId()+",";
                }
            }
        }
        return "input";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            reception=receptionService.get(keyId);
        }else{
            reception=new Reception();
            reception.setCreater(usersService.getLoginInfo());
        }
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManageService.get(f.trim()));
            }
        }
        reception.setFile(fileManageList);
        reception.setLetterNo(letterNo);
        reception.setGuestName(guestName);
        reception.setSex(sex);
        reception.setDepartment(department);
        reception.setPost(post);
        reception.setMainAttache(mainAttache);
        reception.setCount(count);
        reception.setMainName(usersService.get(mainNameId));
        reception.setOtherPerson(otherPerson);
        reception.setReceptionReason(receptionReason);
        reception.setDate(DataUtil.StringToDate(date));
        reception.setContent(content);
        reception.setEatPlace(eatPlace);
        reception.setEatStandard(eatStandard);
        reception.setLivePlace(livePlace);
        reception.setLiveStandard(liveStandard);
        reception.setRemarks(remarks);
        reception.setObject(object);
        reception.setMoney(money);
        reception.setCompany(usersService.getLoginInfo().getCompany());
        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        reception.setIfCentralStaff(ifCentralStaff==1?true:false);
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                receptionService.update(reception);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                receptionService.save(reception, "reception", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        ArrayList<String> list = new ArrayList<String>();
        List<Department> deptList=departmentService.getDepartments("产业中心党政综合办");
        for(Department dept:deptList){
            for(Power power:dept.getPowerSet()){
                Post post = power.getPost();
                if(post.getName().equals("行政负责人")==true){
                    List<Users> usersList=dutyService.getPersons(dept, post);
                    for(Users user:usersList){
                        list.add(user.getId());
                    }
                }
            }
        }
        var1.put("approver", list);
        var2.put("approver", list);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                receptionService.approve(reception, FlowEnum.ProcessState.Running, var2, curDutyId, comment);
            } else {
                keyId = receptionService.commit(reception, "reception", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        Remind remind=new Remind();
        remind.setBussinessKey(reception.getClass().getName());
        remind.setKeyId(keyId);
        remind.setUsers(usersService.get(mainNameId));
        remind.setContent("您有一条接待登记事宜，请查阅");
        remindService.save(remind);
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批1
    public String approve1(){
        System.out.println("#####进入第1步审批");
        reception = receptionService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 2);
        reception.setLeaderExam(leaderExam == 1 ? true : false);
        var1.put("leaderExam", leaderExam);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                if(leaderExam==1){
                    System.out.println("需要中心审核，进2");
                    receptionService.approve(reception, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
                }else{
                    System.out.println("不需要中心审核，结束了");
                    receptionService.approve(reception, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
                }

            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批2
    public String approve2(){
        System.out.println("#####进入第2步审批");
        reception = receptionService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 3);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                receptionService.approve(reception, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批3
    public String approve3(){
        System.out.println("#####进入第3步审批，结束");
        reception = receptionService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 4);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                receptionService.approve(reception, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public String getLetterNo() {
        return letterNo;
    }

    public void setLetterNo(String letterNo) {
        this.letterNo = letterNo;
    }

    public String getGuestName() {
        return guestName;
    }

    public void setGuestName(String guestName) {
        this.guestName = guestName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getPost() {
        return post;
    }

    public void setPost(String post) {
        this.post = post;
    }

    public String getMainAttache() {
        return mainAttache;
    }

    public void setMainAttache(String mainAttache) {
        this.mainAttache = mainAttache;
    }

    public String getCount() {
        return count;
    }

    public void setCount(String count) {
        this.count = count;
    }

    public String getMainNameId() {
        return mainNameId;
    }

    public void setMainNameId(String mainNameId) {
        this.mainNameId = mainNameId;
    }

    public String getOtherPerson() {
        return otherPerson;
    }

    public void setOtherPerson(String otherPerson) {
        this.otherPerson = otherPerson;
    }

    public String getReceptionReason() {
        return receptionReason;
    }

    public void setReceptionReason(String receptionReason) {
        this.receptionReason = receptionReason;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getEatPlace() {
        return eatPlace;
    }

    public void setEatPlace(String eatPlace) {
        this.eatPlace = eatPlace;
    }

    public String getEatStandard() {
        return eatStandard;
    }

    public void setEatStandard(String eatStandard) {
        this.eatStandard = eatStandard;
    }

    public String getLivePlace() {
        return livePlace;
    }

    public void setLivePlace(String livePlace) {
        this.livePlace = livePlace;
    }

    public String getLiveStandard() {
        return liveStandard;
    }

    public void setLiveStandard(String liveStandard) {
        this.liveStandard = liveStandard;
    }

    public String getMoney() {
        return money;
    }

    public void setMoney(String money) {
        this.money = money;
    }

    public String getObject() {
        return object;
    }

    public void setObject(String object) {
        this.object = object;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    public int getLeaderExam() {
        return leaderExam;
    }

    public void setLeaderExam(int leaderExam) {
        this.leaderExam = leaderExam;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public Reception getReception() {
        return reception;
    }

    public void setReception(Reception reception) {
        this.reception = reception;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    public String getExpend() {
        return expend;
    }

    public void setExpend(String expend) {
        this.expend = expend;
    }

    public String getExpendId() {
        return expendId;
    }

    public void setExpendId(String expendId) {
        this.expendId = expendId;
    }
}
